package com.lagou.edu.com.lagou.edu.filter;

import com.alibaba.fastjson.JSON;
import com.fasterxml.jackson.databind.util.JSONPObject;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.CharSet;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.core.annotation.Order;
import org.springframework.core.io.buffer.DataBuffer;
import org.springframework.http.HttpCookie;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.http.server.reactive.ServerHttpResponse;
import org.springframework.stereotype.Component;
import org.springframework.util.MultiValueMap;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

import java.lang.annotation.Annotation;
import java.net.URI;
import java.util.HashMap;
import java.util.Map;

/**
 * 统一鉴权过滤器
 */
@Component
@Slf4j
public class AuthenticationFilter implements GlobalFilter, Order {
    @Override
    public Class<? extends Annotation> annotationType() {
        return null;
    }

    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
        // 从上下⽂中取出request和response对象
        ServerHttpRequest request = exchange.getRequest();
        ServerHttpResponse response = exchange.getResponse();
        // 从request对象中获取客户端ip
        String clientIp = request.getRemoteAddress().getHostString();

        //获取访问路径，不拦截用户微服务和验证码微服务
        URI uri = request.getURI();
        String path = uri.getPath();
        if(path.contains("/user") || path.contains("/code")){
            return chain.filter(exchange);
        }

        //取出Cookie中的token
        MultiValueMap<String, HttpCookie> cookies = request.getCookies();
        if(null == cookies.getFirst("token")) {
            response.setStatusCode(HttpStatus.BAD_GATEWAY); // 状态码
            HttpHeaders httpHeaders = response.getHeaders();
            httpHeaders.setContentType(MediaType.APPLICATION_JSON);
            Map<String, Object> result = new HashMap<>();
            result.put("code", 304);
            result.put("msg", "您未登录，请求已被拒绝");
            String resultStr = JSON.toJSONString(result);
            DataBuffer wrap = response.bufferFactory().wrap(resultStr.getBytes());
            return response.writeWith(Mono.just(wrap));
        }
        return chain.filter(exchange);

    }

    @Override
    public int value() {
        return 1;
    }
}
